package com.pic.mgt.haishin.executer;

import com.pic.mgt.executer.TargetAction;
import com.pic.mgt.haishin.AppointedHaishinRuleConfig;
import com.pic.mgt.haishin.unit.AppointedHaishinBusinessUnit;

public final class AppointedHaishinBusinessUnitExecuter extends HaishinBusinessUnitExecuter {
	private AppointedHaishinBusinessUnit appointedHaishinBusinessUnit;
	private AsgmtAction fixedAsgmtAction;
	private AsgmtAction clientTypeAsgmtAction;
	private AsgmtListener asgmtListener;
	private AppointedHaishinRuleConfig appointedHaishinRuleConfig;
	
	public AppointedHaishinBusinessUnitExecuter(TargetAction targetAction,
									AsgmtAction fixedAsgmtAction,
									AsgmtAction clientTypeAsgmtAction,
									TerminalListener terminalListener,
									AsgmtListener asgmtListener,
									AppointedHaishinRuleConfig appointedHaishinRuleConfig) {
		super(targetAction, terminalListener);

		this.fixedAsgmtAction = fixedAsgmtAction;
		this.clientTypeAsgmtAction = clientTypeAsgmtAction;
		this.asgmtListener = asgmtListener;
		this.appointedHaishinRuleConfig = appointedHaishinRuleConfig;

		// 設定指示檔處理結果通知。
		useAsgmtFileProcessResultNotify();
	}
	
	/*
	 * 設定指示檔理完成通知。
	 * 設定此通知，指示檔處理過程，會針對每一個端末，當完成指示檔的產生時，
	 * 觸發  asgmtProcessNotify() 方法通知。
	 */
	private void useAsgmtFileProcessResultNotify() {
		// 註冊確認檔處理通知
		
		AsgmtFileProcess fixedAsgmtFileProcess = 
							(AsgmtFileProcess)this.fixedAsgmtAction;
		fixedAsgmtFileProcess.setAsgmtListener(this.asgmtListener);
		

		AsgmtFileProcess clientTypeAsgmtFileProcess = 
							(AsgmtFileProcess)this.clientTypeAsgmtAction;
		clientTypeAsgmtFileProcess.setAsgmtListener(this.asgmtListener);
	}
	
	@Override
	protected void buildAsgmtAction() throws BuildAsgmtFileProcessException {
		this.appointedHaishinBusinessUnit =
		 	(AppointedHaishinBusinessUnit)super.business;
		
		/*
		 * 如果指示配信的端末數量大於指示配信分割數量值，則採用分區（會參考端末的 Client Type）
		 * 的方式來給定下載時間； 如果小於則採不分區的方式給定下載時間（下載時間皆相同）。
		 */
		if (this.appointedHaishinBusinessUnit.getAppointedTerminals().size() > 
				this.appointedHaishinRuleConfig.getClientDivideAmount()) {
			this.clientTypeAsgmtAction.build(appointedHaishinBusinessUnit,
					appointedHaishinBusinessUnit.getTargetFilename(),
					appointedHaishinBusinessUnit.getTargetFile().length(),
					appointedHaishinBusinessUnit.getExecutionTime(),
					appointedHaishinBusinessUnit.getAppointedTerminals());
		}
		else {
			this.fixedAsgmtAction.build(appointedHaishinBusinessUnit,
					appointedHaishinBusinessUnit.getTargetFilename(),
					appointedHaishinBusinessUnit.getTargetFile().length(),
					appointedHaishinBusinessUnit.getExecutionTime(),
					appointedHaishinBusinessUnit.getAppointedTerminals());
		}
	}
}
